//
//  GPHistoryController.m
//  Keping
//
//  Created by 23 on 2017/12/7.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "GPHistoryController.h"
#import "GPConversationItem.h"
#import "GPContactModel.h"
#import "GPContactCell.h"
#import "GPProfileItem.h"
#import "GPChatController.h"
#import "GPContactRequest.h"

@interface GPHistoryController ()

/**messages*/
@property(nonatomic,strong) NSMutableArray *messages;

@end

@implementation GPHistoryController

static NSString * const Id = @"conversation";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass(GPContactCell.class) bundle:nil] forCellReuseIdentifier:Id];
    self.tableView.rowHeight = 75.f;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    //添加
    [GPNoticationHelp addObserver:self selector:@selector(loadChatData) name:@"kChatReceivedMessageNotification" object:nil];
    
    [self loadChatData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadChatData];
}

- (void)dealloc
{
    [GPNoticationHelp removeObserver:self];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPContactCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    cell.type = GPContactCellTypeHistory;
    cell.contact = self.messages[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPContactModel * contact = self.messages[indexPath.row];
    
    GPChatViewModel *chatViewModel = [[GPChatViewModel alloc] initWithChatType:EMChatTypeChat conversationId:contact.phone toId:contact.phone toNickName:contact.nickName toAvatarURLPath:contact.profile];
    chatViewModel.uid = contact.partyId;
    
    GPChatController *vc = [[GPChatController alloc] init];
    vc.chatViewModel = chatViewModel;
    [self.navigationController pushViewController:vc animated:YES];
}

//加载聊天会话
- (void)loadChatData
{
    //清空消息
    [self.messages removeAllObjects];
    
    //获取会话消息
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    for (EMConversation *conversation in conversations) {
        GPConversationItem *conversationItem = [[GPConversationItem alloc] initWithConversation:conversation];
        
        //根据环信id从本地获取头像等信息
        NSArray *array = [GPProfileItem selectDBWithHid:conversation.conversationId];
        if (array.count) {
            GPProfileItem *item = array.firstObject;
            conversationItem.uid = item.uid;
            conversationItem.title = item.name;
            conversationItem.avatarURLPath = item.avatarURL;
            conversationItem.coversationUserSex = item.sex;
            conversationItem.coversationUserAge = item.age;
            
            
        }else{
            //如果没有 -- 加载
            //请求用户个人信息
            NSString *url = [@"/intelligent-community/api/biz/ou/v1/partys/getPhone/{phone}.htm" stringByReplacingOccurrencesOfString:@"{phone}" withString:conversation.conversationId];
            GPContactRequest *request = [[GPContactRequest alloc] initWithURL:url];
            [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                
                NSDictionary *dict = request.responseJSONObject;
                NSDictionary *partyView = dict[@"partyView"];
                NSLog(@">>>>>>>>>>>>>smallyou:获取用户消息--->%@", partyView);
                if (partyView == nil) {
                    return;
                }
                //创建GPProfileItem
                GPProfileItem *item = [[GPProfileItem alloc] init];
                item.uid  = partyView[@"Id"];
//                item.hid  = partyView[@"phone"];
                NSString *phone = partyView[@"phone"];
                if ([phone containsString:@"+86"]) {
                    phone = [phone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
                }
                if ([phone containsString:@"+60"]) {
                    phone = [phone stringByReplacingOccurrencesOfString:@"+60" withString:@""];
                }
                item.hid = phone;
                item.name = partyView[@"nickName"];
                item.phone = partyView[@"phone"];
                item.avatarURL = partyView[@"profile"];
                item.realName = partyView[@"realName"];
                item.isBlock = [partyView[@"isBlock"] isEqualToString:@"Y"]?YES:NO;
                item.remarks = partyView[@"remarks"];
                [item insertToDatabase];
                //发起通知
                [GPNoticationHelp postNotificationName:kBuddyUserInfoUpdatedNotificaiton object:nil];
                
            } failure:^(__kindof KBaseRequest * _Nonnull request) {
                NSLog(@">>>>>>>>>>>>>smallyou:获取用户消息失败--->");
            }];
            
        }
        
        GPContactModel *baseBuddyItem = [[GPContactModel alloc] initWithConversation:conversationItem];
        [self.messages addObject:baseBuddyItem];
    }
    
    //刷新表格
    [self.tableView reloadData];
}

#pragma mark - 懒加载
- (NSMutableArray *)messages
{
    if (_messages == nil) {
        _messages = [NSMutableArray array];
    }
    return _messages;
}


@end
